package com.swak.consistency.core.resolve.impls;

import com.swak.annotation.Propagation;
import com.swak.consistency.core.attribute.ConsistencyAttribute;
import com.swak.consistency.core.context.ConsistencyContext;
import com.swak.consistency.core.execption.ConsistencyException;

/**
 * Tcc 事务传播级别： 需要第一个执行
 * 
 * @author lifeng
 * @date 2021年2月5日 上午11:33:23
 */
public class PropagationResolver<T extends ConsistencyContext> extends MultiResolver<T> {

	@Override
	public T acquire(ConsistencyAttribute attribute) {

		// 当前事务对象, 一定会获得一个上下文对象
		T context = super.acquire(attribute);

		// 必须在已有事务中执行
		if (attribute.getPropagation() == Propagation.MANDATORY && !context.isOpenTransaction()) {
			throw new ConsistencyException("必须在已有事务中执行.");
		}

		// 每次都开启一个新事务
		else if (attribute.getPropagation() == Propagation.REQUIRES_NEW && context.isOpenTransaction()) {
			return super.create(attribute);
		}

		// 返回已有的事务
//		else if ((attribute.getPropagation() == Propagation.REQUIRED
//				|| attribute.getPropagation() == Propagation.REQUIRES_NEW) && !context.isOpenTransaction()) {
//			return context;
//		}
		return context;
	}
}